package com.itheima.reggie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    //显示地址栏
    @Override
    public List<Address> findList() {
        //同样对比用户id 进行查询
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(wrapper);
        return addressList;
    }
    //添加地址
    @Override
    public void save(Address address) {
        //设置地址id 符合用户id
        address.setUserId(UserHolder.get().getId());
        //添加地址
        addressMapper.insert(address);
    }
    //设置默认地址
    @Override
    public void setDefault(Long id) {
        //将所有id设置成非默认
        Address address = new Address();
        address.setIsDefault(0);
        //设置跟新
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        //跟新地址
        addressMapper.update(address,wrapper);
        //指定传入id对应的地址为默认地址
        Address address1 = new Address();
        address1.setId(id);
        address1.setIsDefault(1);
        addressMapper.updateById(address1);
    }
    //查询默认地址
    @Override
    public Address findDefault() {
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault, 1);
        return addressMapper.selectOne(wrapper);
    }
    //根据id查询地址
    @Override
    public Address findAddressById(Long id) {
        //根据id查找信息
        Address address = addressMapper.selectById(id);
        return address;
    }
    //更新地址
    @Override
    public void updateAddress(Address address) {
        addressMapper.updateById(address);
    }
    //删除地址
    @Override
    public void deleteAddress(Long ids) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getId,ids);
        addressMapper.delete(wrapper);
    }
}
